﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;
using ObjectBakery.Helpers;
using System.Globalization;
using System.Reflection;
using System.IO;

namespace ObjectBakery
{
    public class ObjectAdapter<T> : ObjectAdapterBase
    {

        public ObjectAdapter(DataTable table)
        {
            this.DataTable = table;
            this.type = typeof(T);
        }

    }

    public class ObjectAdapter : ObjectAdapterBase
    {
        public ObjectAdapter(Type type, DataTable table)
        {
            this.DataTable = table;
            this.type = type;
        }
    }

    public abstract class ObjectAdapterBase
    {
        private DataTable dataTable = new DataTable();

        public DataTable DataTable
        {
            get { return dataTable; }
            set { dataTable = value; }
        }
        protected Type type;

        protected DataSyncHelper syncHelper = new DataSyncHelper();

        public void Fill(IList list)
        {
            dataTable.Rows.Cast<DataRow>().ToList().ForEach(row =>
            {
                var inst = Activator.CreateInstance(type);
                syncHelper.Sync(row, inst);
                list.Add(inst);
            });
        }
        public void Flush(IList list)
        {
            if (list.Count > 0)
                syncHelper.EnsureStructure(list[0], dataTable.NewRow());

            dataTable.Rows.Clear(); //drain existing
            list.Cast<object>().ToList().ForEach(item =>
                {
                    if (item.GetType() == type)
                    {
                        var row = dataTable.NewRow();
                        syncHelper.Sync(item, row);
                        dataTable.Rows.Add(row);
                    }
                    else
                    {
                        //should we throw an exception here?
                    }
                });
        }

    }
}
